<?php
/*
Template Name: WPSPO modèle Défi
*/

get_header(); 

$data = WPSPO_defis::get_options($post->ID);
$valueOptions = json_decode($data->defis_option_value);

// On vérifie si le défi pour un GROUPE a bien les renseignements
$typeSelected = get_post_meta(get_the_ID(), 'wpspo_typedefi', true); // Un groupe ?
$asso_infos = get_user_meta($post->post_author, 'wpspo_asso_infos', true); // infos du groupe ok ?
if($typeSelected>1 && $asso_infos['asso_name']=='') {
    $activDefi = WPSPO_Defis::updateStatus($post->ID, 'pending');
    echo wpspo_redirection( get_permalink(WPSPO_ID_DEFIS).'/', "js" );
} elseif($typeSelected>1) {
    $defiGroupe = true;
    $activDefi = WPSPO_Defis::updateStatus($post->ID, 'publish');
}

if(get_option('wpspo_emails_settings')) { extract(get_option('wpspo_emails_settings')); }
$paramWpspoEmailSetting = get_option('wpspo_emails_settings');

//print_r($data);
/*
 * Défi seul ?
 */
if(isset($valueOptions->share_defis) && $valueOptions->share_defis==1) {
    // Si le Share_defis est à 1, on affiche le formulaire
    $afficheForm = true;
} elseif($valueOptions->share_defis==null && $data->defis_id_user == $current_user->ID) {
    // Si le Share_defis est à 0 mais que c'est le créateur du défi, on affiche le formulaire
    $afficheForm = true;
} else {
    // Sinon on cache le formulaire
    $afficheForm = false; // par default
}

$coordonnees = explode("##", $valueOptions->coord_defis);
$lat = $coordonnees[0]; 
$lng = $coordonnees[1];

// Initialisation
$promesseEnCours = 0;
$promesseValide = 0;
$valideRecolte = false;
$add2Promesse = false;
$prommesseOk = 'Promesse NON Validée';

if( is_user_logged_in() ) {
    
    // Je vérifie si l'user a déjà fait une ou des promesses pour ce défi
    $verifPromesse = WPSPO_Promesse::listByUserByDefi($current_user->ID, $post->ID);
    $countPromEnCours = count($verifPromesse);
    if($countPromEnCours>=1) { $promesseEnCours = 1; }
    /*foreach($verifPromesse as $lapromesse) {
        // TODO: A FINIR => As-til des promesses en cours sur ce défi, 1 ou plusieurs
        echo 'Promesse ID:'.$lapromesse->promesse_id.' --> EN COURS : '.$countPromEnCours.'<br />';
        //print_r($verifPromesse);
    }*/

    // As-t-il validé sa/ses promesses ?
    if($verifPromesse->promesse_valide==1) { $promesseValide = 1; }
    // Si autorisation de plusieurs promesses pour un même défi
    if($paramWpspoSetting['promdefi']==1) { $add2Promesse = true; }

    /*
     * Traitement insertion du montant de sa promesse
     */
    if( !empty($_POST) && $_POST["postpromesse"]==true && ($promesseEnCours == 0 or $add2Promesse == true) ) {
        //Check si le montant n'est pas vide
        if(trim($_POST['promess_montant']) == '') {
            $montantError = __('Please indicate the amount of your pledge!', 'sponsorpress');
            $hasError = true;

        } else {
            $promessMontant = stripslashes(trim($_POST['promess_montant']));
            $promessMontant = str_replace(",", ".", $promessMontant);
            if($valueOptions->mode_defis==2) {
                $type = 2;
            }
        }
        if( ($valueOptions->share_prive==1) && ( ($valueOptions->cle_defis!==$_POST['defi_cle']) or (trim($_POST['defi_cle']) == '') ) ) {
            $cleError = __('The specified key is not valid', 'sponsorpress');
            $hasError = true;
        }
        if(trim($_POST['promess_mot']) != '') {
            $promessMot = stripslashes(trim($_POST['promess_mot']));
        }

        // Si il n'y a pas d'erreur, on insère dans la table
        if(!isset($hasError)) {

            $insertPromesse = WPSPO_Promesse::save($post->ID, $data->defis_id_projet, $current_user->ID, $_POST['post_user_parent'], $promessMot, $promessMontant, $type);
            
            /* Tableau de données supplémentaires pour le mail */
            if($valueOptions->mode_defis==1) { $addValue = stripslashes($valueOptions->text_mode_defis); }
            $montantSentPromesse = str_replace('&euro;','€',wpspo_price($promessMontant,0,0));
            $argsValue = array("#_TOTAL_PROMESSSE" => $montantSentPromesse.'/'.$addValue,);
            /* On envoi le mail */
            $email_content =  wpspo_content_traitement($paramWpspoEmailSetting['email_txt_promesse'], $argsValue);
            
            global $post;
            $id_author = $post->post_author;
            //$attachments = array(WP_CONTENT_DIR . '/uploads/file_to_attach.zip');
            if($defiGroupe==true) {
                $asso_infos = get_user_meta($id_author, 'wpspo_asso_infos', true);
                $auteurEmail = $asso_infos['asso_email'];
            } else {
                $auteurEmail = get_the_author_meta( 'user_email', $id_author );
            }
            $emailTo = $auteurEmail; //TODO Change to $current_user->user_email
            $subject = __( 'Notice of' , 'sponsorpress').' '.get_bloginfo('name');
            $headers[] = 'From: '.get_bloginfo('name').' <'.$emailTo.'>';
            $headers[] = 'Cc: Admin <'.$paramWpspoSetting['emailplugin'].'>';
            
            add_filter('wp_mail_content_type',create_function('', 'return "text/html"; '));
            if( wp_mail( $emailTo, $subject, stripslashes($email_content), $headers ) ) {
                 $emailSent = true;
            } else {
                //echo stripslashes($email_content);
                exit('Erreur envoi mail insert promesse');
            }

            unset($_POST);
            //echo wpspo_redirection( get_permalink($post->ID).'#m', "js" );
            echo wpspo_redirection( get_permalink(WPSPO_ID_COMPTE).'/?&insere=1#mespromesses ' );
        }
    }
}

?>

<div class="content" role="main">

    <?php if (have_posts()) : ?>
        <?php while (have_posts()) : the_post(); ?>
            <article <?php if( !empty( $rv['review'] ) ) echo $rv['review']; post_class('post-listing'); ?>>
                <div class="post-inner">
                    <header class="entry-header">
                        <h1 class="name post-title entry-title entry-title"><?php the_title(); ?></h1>
                    </header>

                <div class="entry-content">

                    <?php
                    $idProjet = get_post_meta($post->ID, 'wpspo_choixprojets', true);
                    $projet = get_post($idProjet);
                    ?>
                    <!-- Projet -->
                    <div style="margin-top:15px;">
                        <strong><?php _e('For this project', 'sponsorpress'); ?></strong><br /><a href="<?php echo get_permalink( $idProjet ); ?>"><?php echo $projet->post_title; ?></a>
                    </div>
                    <!-- Description -->
                    <div style="margin-top:15px;">
                        <strong><?php _e('Description of challenge', 'sponsorpress'); ?></strong><?php the_content(); ?>
                    </div>
                    <!-- Map -->
                    <?php if($paramWpspoSetting['affmaps']==1) { ?>
                        <div class="wpspo-fexible-container">
                            <?php echo do_shortcode('[wpspo_map address="'.$valueOptions->ville_defis.'" width="300px" height="250px"]'); ?>
                        </div>
                    <?php } ?>
                    <!-- Date -->
                    <div style="margin-top:15px;">
                        <strong><?php _e('Date of challenge', 'sponsorpress'); ?></strong><br /><?php echo strftime('%d %B %Y', strtotime($valueOptions->date_defis)); ?>
                    </div>
                    <!-- Ville -->
                    <div style="margin-top:15px;">
                        <strong><?php _e('City', 'sponsorpress'); ?></strong><br /><?php echo $valueOptions->ville_defis; ?>
                    </div>
                    
                    <!-- Encart Auteur -->
                    <?php 

                        if($defiGroupe==true) {
                            $asso_infos = get_user_meta(get_the_author_ID(), 'wpspo_asso_infos', true);
                            $auteurDefi = $asso_infos['asso_name'];
                            $assoc_url = str_replace('http://', '', $asso_infos['asso_url']);
                            $auteurDesc = $asso_infos['asso_desc'];
                            $auteurImg = wpspo_get_user_logo(get_the_author_ID(), 72);
                            if($assoc_url) { 
                                $auteurDefi =  '<a href="http://'.$assoc_url.'" target="_blank">'.$auteurDefi.'</a>'; 
                            } else {
                                $auteurDefi =  $auteurDefi;
                            }
                        } else {
                            $auteurDefi = get_the_author();
                            $auteurDesc = the_author_description();
                            $auteurImg = get_avatar( get_the_author_id() , 72 );
                        }
                    ?>
                    <div id="wpspo-author-meta"><h3><?php _e('Challenge organized by ', 'sponsorpress'); ?> <?php echo $auteurDefi; ?></h3>
                        <?php echo $auteurImg; ?>
                        <p><?php echo $auteurDesc; ?><br /></p>
                        <div id="wpspo-author-info"></div>
                    </div>
                    
                    <!-- Nombre de participants -->
                    <?php
                        // Compte de nombre de promesse / participant
                        $countNbParticipant = WPSPO_Promesse::get_countByDefi($post->ID, 1);
                    ?>
                    <div style="margin-top:15px;">
                        <!-- Formulaire de promesse -->
                        <a name="promesse"></a>
                        <h3 class="wpspo-title"><?php _e('List of participants', 'sponsorpress'); ?> (<?php echo $countNbParticipant; ?>)</h3>
                        <p class="post-meta"></p>
                        <?php //echo 'Auteur : '.$current_user->ID.'-->'.get_the_author_meta( 'ID', get_the_author_ID() );
                            $listParticipant = WPSPO_Promesse::get_byIdDefi($post->ID);
//print_r($listParticipant);
                            if($listParticipant) {

                                echo '<div id="wpspo_table">
                                       <div class="wpspo_row">
                                          <span class="wpspo_cell1">'.__('Name/Organization/Group', 'sponsorpress').'</span>
                                         ';
                                echo '</div>';
                                foreach ( $listParticipant as $participant ) {
                                    $userParticipant = get_userdata($participant->promesse_id_user);
                                    $first_name = $userParticipant-> user_firstname;
                                    $last_name = $userParticipant-> user_lastname;
                                    $nameParticipant = $first_name.' '.$last_name;
                                    if($first_name=='' && $last_name=='') { $nameParticipant = ucfirst($userParticipant->user_login); }
                                    if($valueOptions->text_mode_defis!='' && $valueOptions->mode_defis==1) { 
                                        $textModeDefis = '/ '.$valueOptions->text_mode_defis;
                                    }   
                                    // Pour ceux qui sponsorisent un participant
                                    $listParent = WPSPO_Promesse::get_parentByIdDefi($post->ID, $participant->promesse_id);
                                    $nbSponsor = WPSPO_Promesse::get_countParentByIdDefi($post->ID, $participant->promesse_id);
                                    echo '<div class="wpspo_row">
                                              <span class="wpspo_cell"><b>'.$nameParticipant.'</b>';
                                    /*if($nbSponsor>0) {
                                        echo '<div style="width:100%;"><div style="display: inline-block;list-style: none;margin-right: 5px;text-decoration: none;clear: both;padding: 8.5px 15px;border-radius: 4px;-webkit-border-radius: 4px;background-color:#E15821;color:#FFFFFF;text-align: center">';
                                        printf(_n("%s friend sponsors", "%s friends sponsors", $nbSponsor, 'sponsorpress'), $nbSponsor);
                                        echo '</div></div>';
                                    }*/
                                    echo '<form method="post" name="sponsor_user" action="#m">
                                            <input type="hidden" name="sponsor_user" value="'.$participant->promesse_id_user.'">
                                            <input type="hidden" name="sponsor_user_name" value="'.$nameParticipant.'">
                                           <button style="border: none; background: none; cursor: pointer;"><span style="text-decoration: none; color: #37b8eb;font-style:italic;">'.__('Sponsor him?', 'sponsorpress').'</span></button></form>';
                                    echo '</span>';
                                             /* <span class="wpspo_cell" style="text-align:center;">'.wpspo_price($participant->promesse_montant).' '.stripslashes($textModeDefis).'</span>
                                              <span class="wpspo_cell">'.$participant->promesse_texte.'</span>
                                              ';*/
                                    echo '</div>';
                                    if($listParent) {
                                        foreach ( $listParent as $parent ) {
                                            
                                            $userParent = get_userdata($parent->promesse_id_user);
                                            $first_name_parent = $userParent-> user_firstname;
                                            $last_name_parent = $userParent-> user_lastname;
                                            $nameParent = $first_name_parent.' '.$last_name_parent;
                                    
                                            echo '<div class="wpspo_row">
                                                    <span class="wpspo_cell" style="background-color:#f1f1f1;text-align:center;"><i>'.__('Sponsored  by:', 'sponsorpress').'</i><br />'.$nameParent.'</span>
                                             <span class="wpspo_cell" style="background-color:#f1f1f1;text-align:center;">'.wpspo_price($parent->promesse_montant).' '.stripslashes($textModeDefis).'</span><span class="wpspo_cell" style="background-color:#f1f1f1;">'.$parent->promesse_texte.'</span>';
                                             echo '</div>';
                                        }
                                    }

                                }
                                echo '</div>';

                            } else {
                                echo __('There is no participant.', 'sponsorpress');
                            }
                            ?>
                    </div>
                    
                    <a name="m"></a>
                    <?php 
                    
                    if( $insertPromesse == true ) {
                        echo '<div class="wpspo-confirm" style="margin-top:30px;">'.__('Your promise has been registered. <br /> Thank you for your participation.', 'sponsorpress').'</div>';
                    } 
                    if( $valideRecolte == true ) {
                        echo '<div class="wpspo-confirm" style="margin-top:30px;">'.__('The amount raised by your challenge has been registered and validated. <br /> Thank you for your participation.', 'sponsorpress').'</div>';
                    }
                     
                    if($afficheForm==true and ($insertPromesse != true or $valideRecolte != true) ) { 

                    ?>
                        <a name="mapromesse"></a>
                        <div style="margin-top:25px;">

                            <!-- Formulaire de promesse -->
                            <h1 class="name post-title entry-title entry-title">
                                <?php 
                                    if(isset($_POST["sponsor_user"]) and is_numeric($_POST["sponsor_user"])) { 
                                        echo __('Sponsor', 'sponsorpress').' '.$_POST["sponsor_user_name"];
                                        $userParent = $_POST["sponsor_user"];
                                    } else {
                                        echo __('Participate in this sporting challenge', 'sponsorpress');
                                        $userParent = '';
                                    }
                                ?>
                            </h1>
                            <?php  
                            if( $promesseEnCours == 0 or $add2Promesse == true ) {

                                // Si il n'est pas loggué on refuse
                                if( is_user_logged_in() ) { 
                                    
                                    if($promesseEnCours > 0 and $add2Promesse == true) {
                                            printf( __( 'Vous have a promise being.<br />You can also edit / delete the promise being in %s <br /><br />', 'sponsorpress' ), '<a href="'.get_permalink(WPSPO_ID_COMPTE).'"><strong>'.__('your account.', 'sponsorpress' ).'</strong></a>' );
                                        }


                                   //Si la promesse en cours a été validée, on affiche pour une deuxième promesse
                                   if( ($promesseEnCours == 0 && $promesseValide == 0) or $add2Promesse == true ) {
                            ?>
                                <div style="text-align:center;background-color:#eee;padding:15px;border-radius: 3px;"> 
                                    <form method="post" name="promess_defi" action="#m">
                                        <div style="text-align:left;">
                                            <?php   if($valueOptions->mode_defis==1) { ?>
                                                <?php _e('I want to give', 'sponsorpress'); ?> <input type="text" size="10" name="promess_montant" id="promess_montant" value="<?php echo $promessMontant; ?>" style="font-size: 14px;" /> <?php echo get_wpspo_currency_symbol(); ?> <?php _e('per', 'sponsorpress'); ?> <?php echo stripslashes($valueOptions->text_mode_defis); ?>
                                        <?php 
                                                    } 
                                        if($valueOptions->mode_defis==2) {
                                        ?>
                                            <?php _e('I make a fixed donation', 'sponsorpress'); ?><input type="text" size="10" name="promess_montant" id="promess_montant" value="<?php echo $promessMontant; ?>" style="font-size: 14px;" /><?php echo get_wpspo_currency_symbol(); ?>
                                        <?php
                                        }
                                        ?>
                                        <?php if($montantError != '') { ?>
                                            <span class="error"><?php echo $montantError; ?></span> 
                                        <?php } ?>
                                        <br /><br />
                                        <?php _e('A word of encouragement?', 'sponsorpress'); ?><br /><textarea name="promess_mot" id="promess_mot" rows="3" cols="40"><?php echo $promessMot?></textarea>
                                        <br /><br />
                                        <?php if($valueOptions->share_prive==1 && $valueOptions->cle_defis !='') { ?>
                                            <?php if($cleError != '') { ?>
                                                <span class="error"><?php echo $cleError; ?></span><br /><br />
                                            <?php } ?>
                                            <?php _e('Enter the private key (required)', 'sponsorpress'); ?> <input type="text" size="15" name="defi_cle" id="defi_cle" value="" style="font-size: 14px;" />
                                        <?php } ?>
                                        </div>
                                        <input type="hidden" name="postpromesse" value="true">
                                        <input type="hidden" name="wpspo_choixdefi" value="<?php echo $post->ID; ?>">
                                        <?php
                                            if($userParent) {
                                                echo '<input type="hidden" name="post_user_parent" value="'.$userParent.'">';
                                            }
                                        ?>   
                                        <br /><INPUT type="submit" value="<?php _e('Submit', 'sponsorpress'); ?>">
                                    </form>
                                </div>
                            <div class="clear espace15"></div>
                            <?php 
                                        } else {
                                            echo ''.__('Vous have a promise being. <br /> Please send the amount collected before offering another promise. <br /> You can also edit / delete the promise being in your account.','sponsorpress').'<br /><br />';
                                        }
                                       
                                     } else { ?>

                                <p class="must-log-in"><?php _e('You must be', 'sponsorpress'); ?> <a href="/wp-login.php?redirect_to=<?php echo site_url( $_SERVER['REQUEST_URI'] )?>"><?php _e('logged', 'sponsorpress'); ?></a> <?php _e('to participate in this challenge.', 'sponsorpress'); ?></p>

                            <?php }

                            } else {
                                if($promesseValide==true) { $addPhrase = __('and you have validated', 'sponsorpress'); }
                                echo '<p class="must-log-in" style="margin-bottom:15px;">'.__('You have already made a promise to this challenge', 'sponsorpress').' '.$addPhrase.'.</p>';
                            }
                           
                           ?>

                        </div>
                        <?php } ?>

                 </div>
                </div>
            </article>
        <?php endwhile; ?>
    
        <?php comments_template( '', true ); ?>
    
    <?php endif; ?>

</div><!-- #content -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>
